﻿using System;
using System.Collections.Generic;
using System.IO;
using WcfFlashRemoting.IO;
using WcfFlashRemoting.AmfObjects;

namespace WcfFlashRemoting.IO
{
    internal class AmfReader : IDisposable
    {
        BinaryReader reader;

        public AmfReader(Stream stream)
        {
            reader = new BigEndianBinaryReader(stream);
        }

        public AmfMessage ReadAmfMessage()
        {
            Readers.AmfBaseReader amfReader;
            AmfMessage message = new AmfMessage();
            message.Version = reader.ReadUInt16();

            switch (message.Version)
            {
                case 0:
                    amfReader = new Readers.Amf0Reader(reader);
                    break;
                case 3:
                    amfReader = new Readers.Amf3Reader(reader);
                    break;
                default:
                    throw new InvalidOperationException();
            }
            amfReader.ReadMessage(message);

            return message;
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (reader != null)
            {
                (reader as IDisposable).Dispose();
                reader = null;
            }
        }

        #endregion
    }
}
